package diy

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/widget"
	"golang.org/x/image/colornames"
	"time"
)

var flag = []string{".  ", ".. ", "..."}

type LoadingStruct struct {
	BaseText   string    // 显示的加载文字
	hideChan   chan bool // 通知文字循环关闭的chan
	waitTime   int64     // 文字循环的次数
	CanvasText *canvas.Text
	PopUp      *widget.PopUp
}

func NewLoading(text string, size float32, parent fyne.CanvasObject) *LoadingStruct {
	_loading := &LoadingStruct{
		BaseText: text,
		hideChan: make(chan bool),
		CanvasText: &canvas.Text{
			Text:     text + flag[len(flag)-1],
			Color:    colornames.Gray,
			TextSize: size,
		},
	}
	_canvas := fyne.CurrentApp().Driver().CanvasForObject(parent)
	_loading.PopUp = widget.NewModalPopUp(
		_loading.CanvasText,
		_canvas,
	)
	return _loading
}

func (l *LoadingStruct) Show() *LoadingStruct {
	if l.PopUp.Canvas == nil {
		return nil
	}
	go func() {
		_ticker := time.NewTicker(time.Millisecond * 500)
		defer _ticker.Stop()
		_curIdx := 0
		for {
			select {
			case <-_ticker.C:
				l.waitTime++
				l.CanvasText.Text = l.BaseText + flag[_curIdx]
				l.CanvasText.Refresh()
				_curIdx++
				if _curIdx >= len(flag) {
					_curIdx = 0
				}

				// 等待超过一段时间才show
				if l.waitTime >= 1 {
					l.PopUp.Show()
				}

			case <-l.hideChan:
				return
			}
		}
	}()

	return l
}

func (l *LoadingStruct) Hide() {
	if l == nil {
		return
	}
	l.hideChan <- true
	l.PopUp.Hide()
}
